package com.fly.simple;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.SystemUtils;

import com.fly.simple.utils.FreeMarkerUtil;
import com.fly.simple.utils.ShellExecutor;

import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MainRun
{
    static ScheduledExecutorService service = new ScheduledThreadPoolExecutor(1);
    
    /**
     * 线程池保证程序一直运行
     * 
     * @param args
     */
    public static void main(String[] args)
    {
        // 计算延迟，微调1ms
        long initDelay = 10000L - System.currentTimeMillis() % 10000L - 1;
        service.scheduleAtFixedRate(() -> run(), initDelay, 10000L, TimeUnit.MILLISECONDS);
    }
    
    /**
     * 执行任务
     */
    private static void run()
    {
        try
        {
            if (SystemUtils.IS_OS_WINDOWS)
            {
                log.info("######## {}", ShellExecutor.getDockerInfo());
                return;
            }
            if (SystemUtils.IS_OS_LINUX)
            {
                log.info("will update docker info");
                creatPage("/usr/share/nginx/html/index.html");
                return;
            }
        }
        catch (Exception e)
        {
            log.error(e.getMessage(), e);
        }
    }
    
    /**
     * 更新docker应用页面
     * 
     * @param file
     * @throws IOException
     * @throws TemplateException
     * @see [类、类#方法、类#成员]
     */
    private static void creatPage(String file)
        throws IOException, TemplateException
    {
        // 收集docker信息
        Map<String, Object> model = new HashMap<>(3);
        model.put("date", new Date());
        model.put("map", ShellExecutor.getDockerInfo());
        
        // {mysql5=[3306, 13306], mysql8=[23306], redis-server=[6379]}
        String content = FreeMarkerUtil.renderTemplate("/templates/index.html.ftl", model);
        try (FileWriter writer = new FileWriter(file))
        {
            writer.write(content);
            writer.flush();
        }
    }
}
